//
//  FCAddRelationListViewController.m
//  customerRelation_Example
//
//  Created by 陈文斌 on 2019/2/16.
//  Copyright © 2019 64912907. All rights reserved.
//

#import "FCAddRelationListViewController.h"
#import "FCRelationTyleSheetViewController.h"
#import "FCCustomerRelationRequest.h"
#import "FCEmployeeModel.h"
#import "UIViewController+runtimeCheck.h"
#import "UIViewController+returnBlock.h"
#import "FCAlertViewController.h"
#import "FCCustomerRelationRequest.h"
#import "FCRelationListModel.h"
#import "FCRelationBindRequestViewController.h"
#import "CustomerRelationHeader.h"
#import "FCCrmSupplyRelationOnlyTypeManagerModel.h"

@interface FCAddRelationListViewController ()<UITableViewDelegate>
@property (nonatomic, strong) NSMutableArray *employeeIdArr;
@property (nonatomic, strong) NSMutableArray *relationTypeIdArr;
@property (nonatomic, strong) NSMutableArray *selectedRelationTypeArr;
@property (nonatomic, strong) NSMutableArray<FCEmployeeModel *> *employeeArr;
@property (nonatomic, strong) NSMutableArray *relationTypes;
@property (nonatomic, strong) NSMutableArray *manageRelationTypes;
@property (nonatomic, assign) BOOL isLoadData;

@end

#define CompanyName customerRelationLocaChanged(@"employee_company_name", @"企业全称")
#define RelOwnerName customerRelationLocaChanged(@"法人姓名", @"法人姓名")
#define Phone customerRelationLocaChanged(@"global_general_phone_number", @"手机号码")
#define RelationType customerRelationLocaChanged(@"上下游关系", @"上下游关系")
#define Employee customerRelationLocaChanged(@"指派我司联系人", @"指派我司联系人")

@implementation FCAddRelationListViewController
- (NSMutableArray *)selectedRelationTypeArr{
    if (!_selectedRelationTypeArr) {
        _selectedRelationTypeArr = [NSMutableArray array];
        
    }
    return _selectedRelationTypeArr;
}
- (NSMutableArray *)manageRelationTypes{
    if (!_manageRelationTypes) {
        _manageRelationTypes = [NSMutableArray array];
    }
    return _manageRelationTypes;
}
- (NSMutableArray *)relationTypes{
    if (!_relationTypes) {
        _relationTypes = [NSMutableArray array];
    }
    return _relationTypes;
}
- (NSMutableArray *)employeeIdArr{
    if (!_employeeIdArr) {
        _employeeIdArr = [NSMutableArray new];
    }
    return _employeeIdArr;
}
- (NSMutableArray *)relationTypeIdArr{
    if (!_relationTypeIdArr) {
        _relationTypeIdArr = [NSMutableArray new];
    }
    return _relationTypeIdArr;
}
- (NSMutableArray<FCEmployeeModel *> *)employeeArr{
    if (!_employeeArr) {
        _employeeArr = [NSMutableArray array];
    }
    return _employeeArr;
}

- (void)setupContentUI{
    self.settingDelegate = self;
    self.tableView.scrollEnabled = NO;
    self.tableView.delegate = self;
    
    tableObj *companyName = [tableObj itemWithTitle:CompanyName value:@"" placeHolder:customerRelationLocaChanged(@"global_prompt_name_example_notice", @"如：xxx有限公司")  cellType:FCTableCellInput];
    companyName.choice = YES;
    
    [companyName addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    
    tableObj *ownerName = [tableObj itemWithTitle:RelOwnerName value:@"" placeHolder:customerRelationLocaChanged(@"请输入企业创建者法人姓名", @"请输入企业创建者法人姓名") cellType:FCTableCellInput];
    ownerName.choice = YES;
    [ownerName addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    
    tableObj *phone = [tableObj itemWithTitle:Phone value:@"" placeHolder:customerRelationLocaChanged(@"请输入企业创建者手机号码", @"请输入企业创建者手机号码")  cellType:FCTableCellInput];
    phone.choice = YES;
    phone.keyboardType = UIKeyboardTypePhonePad;
    [phone addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    
    tableObj *relationType = [tableObj itemWithTitle:RelationType value:@"" placeHolder:customerRelationLocaChanged(@"global_general_choose_please", @"请选择") cellType:FCTableCellChoice];
    relationType.choice = YES;
    [relationType addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    
    tableObj *employee = [tableObj itemWithTitle:Employee value:@"" placeHolder:customerRelationLocaChanged(@"global_general_choose_please", @"请选择") cellType:FCTableCellChoice];
    employee.choice = YES;
    [employee addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionNew context:nil];
    
    self.contentArr = [NSMutableArray arrayWithObjects:@[companyName, relationType, employee,],@[phone, ownerName], nil];
}

- (void)dealloc
{
    for (NSArray *arr in self.contentArr) {
        for (tableObj *obj in arr) {
            [obj removeObserver:self forKeyPath:@"value"];
        }
    }
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    BOOL isEnabled = YES;
    for (NSArray *arr in self.contentArr) {
        for (tableObj *obj in arr) {
            if (!(obj.value.length > 0)) {
                isEnabled = NO;
            }
        }
    }
    self.buttonStateBlock(isEnabled);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupContentUI];
}

#pragma mark - delegate
-(UITableViewCell*)getOthertableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}

-(void)getComontableView:(UITableView *)tableView andTableViewCell:(UITableViewCell*)cell cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.selectionStyle = UIAccessibilityTraitNone;
}

// 键盘将弹起
- (void)keyboardWillShowWithNotification:(NSNotification *)notification cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMGLog(@"%ld",indexPath.section);
}

// 键盘将关闭
- (void)keyboardWillHideWithNotification:(NSNotification *)notification cellForRowAtIndexPath:(NSIndexPath *)indexPath andkeyBorardTool:(id)keyBorardTool {
    NSIndexPath *index = [self getReturnCellIndexWithCellName:CompanyName];
    if (index == indexPath) {
        NSLog(@"检测企业是否注册");
        tableObj *companyNameObj = [self getReturnCellWithCellName:CompanyName];
        if (companyNameObj.value.length > 0) {
            NSDictionary *param = @{
                                    @"companyName": companyNameObj.value
                                    };
            WJCWeakSelf
            [FCCustomerRelationRequest getCompanyInfoWithArgs:param success:^(id resultObj) {
                NSLog(@"判断企业是否认真结果：%@",resultObj);
                NSArray *companyArr = resultObj[@"data"][@"companyByNamePhone"];
                if(companyArr.count == 0) return ;
                for (NSDictionary *company in companyArr) {
                    if ([company[@"verifyStatus"] isEqualToString:@"Pass"]) {
                        tableObj *relOwnerNameObj = [weakSelf getReturnCellWithCellName:RelOwnerName];
                        relOwnerNameObj.value = company[@"legalPersonName"];
                        
                        tableObj *phoneObj = [weakSelf getReturnCellWithCellName:Phone];
                        phoneObj.value = company[@"owner"][@"phoneNumber"];
                        
                        [weakSelf.tableView reloadData];
                        break;
                    }
                }
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
            }];
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self getReturnCellIndexWithCellName:RelationType] == indexPath) {
        [self getCacheDataWithIndex:indexPath];
    }
    if ([self getReturnCellIndexWithCellName:Employee] == indexPath) {
        NSDictionary *cache = [FCFuChengCacheTool getHttpCacheWithUrlString:@"crmSupplyRelationOnlyTypeManager" parameters:nil];
        FCCrmSupplyRelationOnlyTypeManagerModel *relationOnlyTypeManagerModel = [FCCrmSupplyRelationOnlyTypeManagerModel mj_objectWithKeyValues: cache];
        UIViewController *con = [self pushAppControllerWithControllerName:@"FCChoiceEmployeeListViewController" andObjectData:@{@"choicedArr": self.employeeArr, @"departGroupIdArr": relationOnlyTypeManagerModel.companyDepartmentId ? @[relationOnlyTypeManagerModel.companyDepartmentId] : @[]} andTitle:Employee];
        WJCWeakSelf
        con.idBlock = ^(NSArray<FCEmployeeModel *> *employees) {
            weakSelf.employeeArr = employees;
            NSString *typeStr = @"";
            if (weakSelf.employeeIdArr.count > 0) {
                [weakSelf.employeeIdArr removeAllObjects];
            }
            for (FCEmployeeModel *employeeModel in employees) {
                XMGLog(@"%@",employeeModel.Name);
                typeStr = [NSString stringWithFormat:@"%@、%@",typeStr, employeeModel.Name];
                [weakSelf.employeeIdArr addObject:employeeModel.Id];
            }
            if (typeStr.length > 1) {
                typeStr = [typeStr substringFromIndex:1];
            }
            weakSelf.contentArr[indexPath.section][indexPath.row].value = typeStr;
            [tableView reloadData];
        };
    }
}

- (void)showSheet{
    tableObj *companyNameObj = [self getReturnCellWithCellName:CompanyName];
    tableObj *ownerNameObj = [self getReturnCellWithCellName:RelOwnerName];
    tableObj *phoneObj = [self getReturnCellWithCellName:Phone];
    tableObj *relationTypeObj = [self getReturnCellWithCellName:RelationType];
    tableObj *employeeObj = [self getReturnCellWithCellName:Employee];
    
    if ([companyNameObj.value isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:customerRelationLocaChanged(@"company_approve_companyname_no_input", @"请输入企业全称")];
        return;
    }
    if ([ownerNameObj.value isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:customerRelationLocaChanged(@"请输入企业创建者法人姓名", @"请输入企业创建者法人姓名")];
    }
    if ([phoneObj.value isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:customerRelationLocaChanged(@"请输入企业创建者手机号码", @"请输入企业创建者手机号码")];
        return;
    }
    if ([relationTypeObj.value isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:customerRelationLocaChanged(@"请选择上下游关系", @"请选择上下游关系")];
        return;
    }
    if ([employeeObj.value isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:customerRelationLocaChanged(@"请选择指派我司联系人", @"请选择指派我司联系人")];
        return;
    }
    
    
    BOOL isSelManagerType = NO;
    if (self.manageRelationTypes.count > 0) {
        for (FCRelationTypeModel *managerType in self.manageRelationTypes) {
            for (FCRelationTypeModel *selType in self.selectedRelationTypeArr) {
                if ([managerType.Id isEqualToString:selType.Id]) {
                    isSelManagerType = YES;
                    break;
                }
            }
        }
    }
    if ([FCEmployeeModel empCompanyIsMine]) {
        isSelManagerType = YES;
    }
    
    if (!isSelManagerType) {
        [SVProgressHUD showInfoWithStatus:customerRelationLocaChanged(@"至少选择一个自己负责的分组", @"至少选择一个自己负责的分组")];
        return;
    }
    
    FCAlertViewController *alertVC  = [[FCAlertViewController alloc] initWithTitle:customerRelationLocaChanged(@"核对信息", @"核对信息") andSubTitle:nil andAlertType:FCAlertContainer];
    alertVC.addCustomContainerBlock = ^UIView *(UIView *containerView) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 178)];
        [containerView addSubview:view];
//        [view mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.and.left.and.right.equalTo(containerView).offset(0);
//        }];
        
        UILabel *title = [UILabel new];
        [view addSubview:title];
        title.text = customerRelationLocaChanged(@"核对信息", @"核对信息");
        title.font = Bfont17;
        title.textColor = FCTxtColor;
        title.textAlignment = NSTextAlignmentCenter;
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view.mas_top).offset(20);
            make.centerX.mas_equalTo(0);
        }];
        
        UILabel *companyNameLabel = [UILabel new];
        [view addSubview:companyNameLabel];
        companyNameLabel.text = companyNameObj.value;
        companyNameLabel.numberOfLines = 1;
        companyNameLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        companyNameLabel.font = font15;
        companyNameLabel.textColor = FCTxtColor;
        companyNameLabel.textAlignment = NSTextAlignmentCenter;
        [companyNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(title.mas_bottom).mas_offset(10);
            make.centerX.mas_equalTo(0);
            make.width.mas_equalTo(230);
        }];
        
        UILabel *relationTypeLabel = [UILabel new];
        [view addSubview:relationTypeLabel];
        relationTypeLabel.text = relationTypeObj.value;
        relationTypeLabel.numberOfLines = 1;
        relationTypeLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        relationTypeLabel.font = font15;
        relationTypeLabel.textColor = FCTxtColor;
        relationTypeLabel.textAlignment = NSTextAlignmentCenter;
        [relationTypeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(companyNameLabel.mas_bottom).mas_offset(0);
            make.centerX.mas_equalTo(0);
            make.width.mas_equalTo(230);
        }];
        
        UILabel *relMobileLabel = [UILabel new];
        [view addSubview:relMobileLabel];
        relMobileLabel.text = [NSString stringWithFormat:@"%@%@", customerRelationLocaChanged(@"负责人手机号码", @"负责人手机号码"), phoneObj.value];
        relMobileLabel.numberOfLines = 2;
        relMobileLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        relMobileLabel.font = font15;
        relMobileLabel.textColor = FCTxtColor;
        relMobileLabel.textAlignment = NSTextAlignmentCenter;
        [relMobileLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(relationTypeLabel.mas_bottom).mas_offset(0);
            make.centerX.mas_equalTo(0);
            make.width.mas_equalTo(230);
            make.bottom.equalTo(view).offset(-16);
        }];
        
        view.height = [self getLabelHeightWithLabelArr:@[title,companyNameLabel,relationTypeLabel,relMobileLabel] andWidth:containerView.width - 32] + 16 + 10 + 20;
        
        return view;
    };
    
    [alertVC addAction:[FCAlertAction actionWithTitle:customerRelationLocaChanged(@"pay_account_confirm_info_dg_btn_lt", @"返回修改") style:FCAlertActionDefault handler:^(FCAlertAction *action) {
        
    }]];
    WJCWeakSelf
    [alertVC addAction:[FCAlertAction actionWithTitle:customerRelationLocaChanged(@"pay_account_confirm_info_dg_rt", @"确认无误") style:FCAlertActionDefault handler:^(FCAlertAction *action) {
        [SVProgressHUD showWithStatus:customerRelationLocaChanged(@"添加上下游关系", @"添加上下游关系")];
        NSDictionary *args = @{
                               @"relCompanyName": companyNameObj.value,
                               @"relOwnerName": ownerNameObj.value,
                               @"relOwnerMobile": phoneObj.value,
                               @"addEmpIds": self.employeeIdArr,
                               @"addTypeIds": self.relationTypeIdArr
                               };
        
        [FCCustomerRelationRequest addRelationRequestsWithArgs:args success:^(NSDictionary *resultObj) {
            [SVProgressHUD showSuccessWithStatus:customerRelationLocaChanged(@"发送成功", @"发送成功")];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:CrmSupplyRelationChanged object:nil];
                [weakSelf.navigationController popViewControllerAnimated:YES];
//            });
            
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
        }];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:^{ }];
}

- (CGFloat)getLabelHeightWithLabelArr:(NSArray *)arr andWidth:(CGFloat)width{
    CGFloat height = 0.0f;
    for (UILabel *label in arr) {
        height += [label sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)].height;
    }
    return height;
}

// 获取缓存数据
- (void)getCacheDataWithIndex:(NSIndexPath *)indexPath{
    //获取缓存数据
//    WJCWeakSelf
    if ([FCEmployeeModel empCompanyIsMine]) {
        self.manageRelationTypes = [NSMutableArray array];
    } else {
        NSMutableDictionary *relationTypeParam = [NSMutableDictionary dictionary];
        relationTypeParam[@"isManage"] = @"YES";
        NSArray *manageRelationTypeCache = [FCFuChengCacheTool getHttpCacheWithUrlString:FCCrmSupplyRelationTypesDataKey parameters:relationTypeParam];
        self.manageRelationTypes = [FCRelationTypeModel mj_objectArrayWithKeyValuesArray:manageRelationTypeCache];
    }
    
//    NSArray *cache = [FCFuChengCacheTool getHttpCacheWithUrlString:FCCrmSupplyRelationTypesDataKey parameters:nil];
//    self.relationTypes = [FCRelationTypeModel mj_objectArrayWithKeyValuesArray:cache];
//    if (/*self.relationTypes.count && */self.manageRelationTypes.count) {
//        [self showRelationTypeSelectWithTableObj:weakSelf.contentArr[indexPath.section][indexPath.row]];
//    } else {
        if (!self.isLoadData) {
            self.relationTypes = [NSMutableArray new];
            [self getRelationTypeWithIndexPath:indexPath];
        }
//    }
}

- (void)getRelationTypeWithIndexPath:(NSIndexPath *)indexPath{
    self.isLoadData = YES;
    
    NSNumber *take = @(15);
    NSDictionary *args = @{@"enable": @(YES),
                           @"take": take,
                           @"skip": @(self.relationTypes.count)
                           };
    
    WJCWeakSelf
    [FCCustomerRelationRequest getCrmSupplyRelationTypeWithArgs:args success:^(id resultObj) {
        FCRelationTypeListModel *relationTypesModel = [FCRelationTypeListModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationTypes"]];
        [weakSelf.relationTypes addObjectsFromArray:relationTypesModel.items];
        if (weakSelf.relationTypes.count >= relationTypesModel.pageInfo.total) {
            XMGLog(@"relationType 全部请求完成");
            weakSelf.isLoadData = NO;
            //缓存
            NSArray *cache = [FCRelationTypeModel mj_keyValuesArrayWithObjectArray:self.relationTypes];
            [FCFuChengCacheTool saveHttpCache:cache urlString:FCCrmSupplyRelationTypesDataKey parameters:nil];
            
            [self showRelationTypeSelectWithTableObj:weakSelf.contentArr[indexPath.section][indexPath.row]];
        } else {
            XMGLog(@"relationType 继续请求");
            [self getRelationTypeWithIndexPath:indexPath];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        XMGLog(@"%@", error);
        self.isLoadData = NO;
    }];
}

- (void)showRelationTypeSelectWithTableObj:(tableObj *)obj{
    WJCWeakSelf
    FCRelationTyleSheetViewController *sheetVC = [[FCRelationTyleSheetViewController alloc] init];
    sheetVC.relationTypeArr = self.relationTypes;
    sheetVC.priorityRelationTypeArr = self.manageRelationTypes;
    sheetVC.selectedRelationTypeArr = self.selectedRelationTypeArr;
    sheetVC.completeBlock = ^(NSMutableArray<FCRelationTypeModel *> * _Nonnull selectedRelationTypes) {
        NSString *typeStr = @"";
        weakSelf.selectedRelationTypeArr = selectedRelationTypes;
        if (weakSelf.relationTypeIdArr.count > 0) {
            [weakSelf.relationTypeIdArr removeAllObjects];
        }
        for (FCRelationTypeModel *typeModel in selectedRelationTypes) {
            XMGLog(@"%@",typeModel.name);
            typeStr = [NSString stringWithFormat:@"%@、%@",typeStr, typeModel.name];
            [weakSelf.relationTypeIdArr addObject:typeModel.Id];
        }
        if (typeStr.length > 1) {
            typeStr = [typeStr substringFromIndex:1];
        }
        obj.value = typeStr;
        [weakSelf.tableView reloadData];
    };
    sheetVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    sheetVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    [SVProgressHUD dismiss];
    [self presentViewController:sheetVC animated:YES completion:^{ }];
}

@end
